<?php
declare (strict_types = 1);

namespace app\command\Shopify;

use app\constant\CommonConstant;
use app\constant\ModelConstant;
use app\event\PushOrderToShopify;
use app\model\Notify;
use app\model\Orders;
use app\model\ShopsPayment;
use app\queue\CompleteDraftQueue;
use app\service\shopify\action\rest\DraftOrderRest;
use app\service\shopify\action\rest\OrderRest;
use app\trait\ShopifyTrait;
use Carbon\Carbon;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Event;
use think\facade\Log;
use think\facade\Queue;
use think\helper\Str;
use function Clue\StreamFilter\fun;

class CreateOrder extends Command
{
    use ShopifyTrait;
    protected $isFilter = false;
    protected $expireTime = 10;
    protected function configure()
    {
        // 指令配置
        $this->setName('shopify:create')
            ->addOption('order_id',null,Option::VALUE_OPTIONAL,'订单ID')
            ->addOption('shop_id',null,Option::VALUE_OPTIONAL,'店铺ID')
            ->addOption('trade_id',null,Option::VALUE_OPTIONAL,'交易ID')
            ->setDescription('创建订单并且完成');
    }

    protected function execute(Input $input, Output $output)
    {
        try {
            $options = $input->getOptions();
            foreach ($options as $key => $option){
               if(in_array($key,['order_id','trade_id']) && !empty($option)) $this->isFilter = true;
            }

            $orderList = $this->getPurchaseUnPayList($options);
            //dump($orderList);
            if ($orderList->isEmpty()) return false;
            foreach ($orderList as $order) {
                $now = time();
                $second = ($now - $order->created_int) / 60;
                $minutes = ceil($second);
                if($this->isFilter) $minutes = 30;
                if ($minutes > 10) {
                    if(!$this->checkOrderStatus($order)) continue;
                    dump('*************正在处理订单: ' . $order->id . '*************');
                    $orderNoArr = explode(',', $order->order_no);
                    $len = count($orderNoArr);
                    if(count($orderNoArr) > 1) {
                        if($order->payment->pay_method == ShopsPayment::PAY_METHOD_PAYPAL){
                            $orderNoArr = array_filter($orderNoArr,function ($item){
                                return !Str::contains($item,'#');
                              }
                            );
                        }
                        if(count($orderNoArr) > 1){
                            unset($orderNoArr[$len - 1]);
                            $order->order_no = implode(',', $orderNoArr);
                            $order->save();
                        }
                    }

                    //Queue::push(CompleteDraftQueue::class, $order->id, 'shopify');//完成shopify队列
                    //$this->complete_draft($order);
                    Event::trigger("PushOrder",new PushOrderToShopify($order));
                }
            }
        }catch (\Exception $e){
            dump($e);
        }



    }

    protected function getPurchaseUnPayList($options)
    {
        $today= [
            Carbon::yesterday()->startOfDay()->timestamp,//昨天
            Carbon::today()->endOfDay()->timestamp,//今天
        ];
        return Orders::query()
                        //过滤订单
                       ->when(isset($options['order_id']) && !empty($options['order_id']),function($q) use ($options){
                           return $q->whereIn('id',explode(',',$options['order_id']));
                       })
                      //过滤订单
                        ->when(isset($options['trade_id']) && !empty($options['trade_id']),function($q) use ($options){
                            return $q->where('transaction_id','like','%' . $options['trade_id'] . '%');
                        })
                        //过滤店铺
                        ->when(isset($options['shop_id']) && !empty($options['shop_id']),function($q) use ($options){
                            return $q->whereIn('shop_id',explode(',',$options['shop_id']));
                        })
                      //当天
                          ->when(!$this->isFilter,function ($q) use($today){
                              return $q->whereBetween('created_int',$today);
                          })
                       ->when(!$this->isFilter,function ($q){
                            return $q->whereBetween('is_completed',ModelConstant::STATUS_OFF);
                        })
                        ->when(!$this->isFilter,function ($q) {
                            return $q->whereBetween('pay_status',ModelConstant::STATUS_ON);
                        })
                        ->when(!$this->isFilter,function ($q) {
                            return $q->whereBetween('order_status',ModelConstant::STATUS_OFF);
                        })
                      ->whereNull('order_id')
                      //->limit(2)
                      ->select();

    }


    //检查AB 异步通知
    public function checkOrderStatus(Orders $order)
    {

        //贝宝支付
        if($order->payment->pay_method == ShopsPayment::PAY_METHOD_PAYPAL || $this->isFilter) {
            $this->handleWithFirstPay($order);
            return true;
        };
        $notifys = Notify::query()
            ->where('order_id',$order->id)
            ->whereIn('type',[Notify::TYPE_CAPTURE_PURCHASE,Notify::TYPE_NOTIFY])
            ->order('id','asc')
            ->select()
            ->toArray();
        if(empty($notifys)) return false;
        $transactionIds = explode(',',$order->transaction_id);
        $abResult = [];
        $firstPayResult = $secondPayResult = false;//区分首次购买+二次购买
        //异步加购处理
        foreach ($notifys as $notify){
            $params = $notify['params'];
            foreach ($transactionIds as $transactionId){
                if(isset($params['data']) && !empty($params['data'])){
                    $data = $params['data'];
                    if($data['tradeNo'] == $transactionId){
                        $isRepurchase = $params['is_repurchase'] ?? 0;
                        $abResult[] = ['transactionId'=>$transactionId,'order_status'=>$data['orderStatus'],'is_repurchase'=>$isRepurchase];
                        if($isRepurchase){
                            $secondPayResult = $data['orderStatus'] == 'success';
                        }else{
                            $firstPayResult = $data['orderStatus'] == 'success';
                        }
                    }
                }
            }
        }
        tplog(sprintf("订单%s异步通知结果： ",$order->id),$abResult,'asiabill');
        if($firstPayResult){//首次购买
            if($secondPayResult){//加购结果
                $this->handleWithSecondPay($order);//处理加购
                return true;
            }else{
                $this->handleWithFirstPay($order);//处理首购
                return true;
            }
        }else{
            $this->handleWithFailPay($order);
            return false;
        }
    }

    //处理首购
    protected function handleWithFirstPay(Orders $order)
    {
        $order->pay_status = ModelConstant::STATUS_ON;
        $order->is_repurchase = ModelConstant::STATUS_OFF;
        $order->is_completed = ModelConstant::STATUS_OFF;
        $order->repurchase_price = '0.00';
        $order->save();
        $order->items()->where('is_repurchase', ModelConstant::STATUS_ON)->delete();
    }

    //处理加购
    protected function handleWithSecondPay(Orders $order)
    {
        $order->pay_status = ModelConstant::STATUS_ON;
        $order->is_completed = ModelConstant::STATUS_ON;
        $order->save();
    }

    //处理失败订单
    protected function handleWithFailPay(Orders $order)
    {
        $order->pay_status = ModelConstant::STATUS_OFF;
        $order->order_status = Orders::ORDER_STATUS_FAIL;
        $order->save();
    }



}
